<template>
  <view class="sql-history-page">
    <!-- 头部 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">🗄️ SQL历史记录和回滚管理</text>
        <text class="header-subtitle">数据库：seekreal | 用户：root | 服务器：localhost</text>
      </view>
    </view>
    
    <!-- 数据库状态仪表板 -->
    <view class="dashboard">
      <view class="stat-card" v-for="(stat, index) in stats" :key="index">
        <text class="stat-label">{{ stat.label }}</text>
        <text class="stat-value">{{ stat.value }}</text>
      </view>
    </view>
    
    <!-- 控制按钮 -->
    <view class="controls">
      <button class="btn btn-primary" @click="refreshData">🔄 刷新数据</button>
      <button class="btn btn-success" @click="createBackup">💾 创建备份</button>
      <view class="last-update">最后更新：{{ lastUpdate }}</view>
    </view>
    
    <!-- 提示信息 -->
    <view v-if="alertMessage" class="alert" :class="alertType">
      {{ alertMessage }}
    </view>
    
    <!-- SQL历史记录表格 -->
    <view class="history-table">
      <view class="table-header">
        <text class="header-cell">时间</text>
        <text class="header-cell">操作类型</text>
        <text class="header-cell">文件名</text>
        <text class="header-cell">大小</text>
        <text class="header-cell">备份类型</text>
        <text class="header-cell">操作</text>
      </view>
      
      <view v-if="loading" class="loading">
        <text>正在加载SQL历史记录...</text>
      </view>
      
      <view v-else-if="historyList.length === 0" class="empty">
        <text>暂无SQL历史记录</text>
      </view>
      
      <view v-else class="table-body">
        <view v-for="(item, index) in historyList" :key="index" class="table-row">
          <text class="table-cell">{{ formatTime(item.timestamp) }}</text>
          <view class="table-cell">
            <text class="operation-tag" :class="getOperationTagClass(item.operation)">
              {{ item.operation }}
            </text>
          </view>
          <text class="table-cell filename">{{ truncateFileName(item.fileName) }}</text>
          <text class="table-cell">{{ item.size }}</text>
          <text class="table-cell">{{ item.type }}</text>
          <view class="table-cell">
            <button 
              class="btn btn-danger btn-sm" 
              @click="showRollbackModal(item)"
              :disabled="!item.canRollback"
            >
              🔄 一键回滚
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 回滚确认模态框 -->
    <view v-if="showModal" class="modal" @click="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">⚠️ 确认回滚操作</text>
          <text class="close-btn" @click="closeModal">&times;</text>
        </view>
        
        <view class="modal-body">
          <text class="modal-text">您即将回滚到以下备份点：</text>
          <view class="backup-info">
            <text class="backup-name">{{ currentRollbackFile?.fileName }}</text>
            <text class="backup-details">
              操作：{{ currentRollbackFile?.operation }} | 
              时间：{{ formatTime(currentRollbackFile?.timestamp) }} | 
              大小：{{ currentRollbackFile?.size }}
            </text>
          </view>
          
          <view class="form-group">
            <text class="form-label">回滚原因：<text class="optional">(可选)</text></text>
            <textarea 
              v-model="rollbackReason" 
              class="form-textarea" 
              placeholder="请输入回滚原因（可选）..."
              rows="3"
            ></textarea>
          </view>
          
          <text class="warning-text">
            ⚠️ 注意：此操作将覆盖当前数据库状态，系统会自动创建回滚前备份。
          </text>
        </view>
        
        <view class="modal-footer">
          <button class="btn btn-primary" @click="closeModal">取消</button>
          <button class="btn btn-danger" @click="confirmRollback">确认回滚</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'SqlHistory',
  data() {
    return {
      loading: true,
      stats: [
        { label: '数据库大小', value: '加载中...' },
        { label: '用户数量', value: '加载中...' },
        { label: '任务数量', value: '加载中...' },
        { label: '团队数量', value: '加载中...' }
      ],
      historyList: [],
      lastUpdate: '加载中...',
      alertMessage: '',
      alertType: '',
      showModal: false,
      currentRollbackFile: null,
      rollbackReason: ''
    }
  },
  
  onLoad() {
    this.loadDashboardData()
    this.loadSqlHistory()
  },
  
  methods: {
    // 加载仪表板数据
    async loadDashboardData() {
      try {
        const response = await uni.request({
          url: '${NETWORK_CONFIG.API_BASE_URL}/sql-history/api/status',
          method: 'GET'
        })
        
        if (response.data.success) {
          const data = response.data
          this.stats = [
            { label: '数据库大小', value: data.databaseSize },
            { label: '用户数量', value: data.tableStats.users || 0 },
            { label: '任务数量', value: data.tableStats.tasks || 0 },
            { label: '团队数量', value: data.tableStats.teams || 0 }
          ]
          this.lastUpdate = '最后更新：' + new Date().toLocaleString()
        } else {
          this.showAlert('获取数据库状态失败：' + response.data.message, 'danger')
        }
      } catch (error) {
        this.showAlert('加载仪表板数据失败：' + error.message, 'danger')
      }
    },
    
    // 加载SQL历史记录
    async loadSqlHistory() {
      try {
        this.loading = true
        const response = await uni.request({
          url: '${NETWORK_CONFIG.API_BASE_URL}/sql-history/api/history',
          method: 'GET'
        })
        
        if (response.data.success) {
          this.historyList = response.data.sqlHistory || []
        } else {
          this.showAlert('获取SQL历史失败：' + response.data.message, 'danger')
        }
      } catch (error) {
        this.showAlert('加载SQL历史失败：' + error.message, 'danger')
      } finally {
        this.loading = false
      }
    },
    
    // 创建备份
    async createBackup() {
      try {
        this.showAlert('正在创建备份，请稍候...', 'info')
        
        const response = await uni.request({
          url: '${NETWORK_CONFIG.API_BASE_URL}/api/database-backup/create',
          method: 'POST',
          data: {
            reason: 'manual_web_backup'
          }
        })
        
        if (response.data.success) {
          this.showAlert('✅ 备份创建成功！', 'success')
          this.loadSqlHistory() // 刷新历史记录
        } else {
          this.showAlert('❌ 备份创建失败：' + response.data.message, 'danger')
        }
      } catch (error) {
        this.showAlert('创建备份失败：' + error.message, 'danger')
      }
    },
    
    // 刷新数据
    refreshData() {
      this.loadDashboardData()
      this.loadSqlHistory()
      this.showAlert('数据已刷新', 'success')
    },
    
    // 显示回滚确认模态框
    showRollbackModal(item) {
      this.currentRollbackFile = item
      this.rollbackReason = ''
      this.showModal = true
    },
    
    // 关闭模态框
    closeModal() {
      this.showModal = false
      this.currentRollbackFile = null
    },
    
    // 确认回滚
    async confirmRollback() {
      if (!this.currentRollbackFile) return
      
      const reason = this.rollbackReason.trim() || '一键回滚操作（未填写原因）'
      
      try {
        this.showAlert('正在执行回滚操作，请稍候...', 'info')
        this.closeModal()
        
        const response = await uni.request({
          url: '${NETWORK_CONFIG.API_BASE_URL}/sql-history/api/rollback',
          method: 'POST',
          data: {
            backupFileName: this.currentRollbackFile.fileName,
            reason: reason
          }
        })
        
        if (response.data.success) {
          this.showAlert(`🎉 回滚成功！已回滚到：${response.data.rolledBackTo}`, 'success')
          // 刷新数据
          setTimeout(() => {
            this.refreshData()
          }, 2000)
        } else {
          this.showAlert('❌ 回滚失败：' + response.data.message, 'danger')
        }
      } catch (error) {
        this.showAlert('回滚操作失败：' + error.message, 'danger')
      }
    },
    
    // 显示提示信息
    showAlert(message, type = 'info') {
      this.alertMessage = message
      this.alertType = type
      
      // 3秒后自动隐藏
      setTimeout(() => {
        this.alertMessage = ''
      }, 3000)
    },
    
    // 格式化时间
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleString()
    },
    
    // 获取操作标签样式类
    getOperationTagClass(operation) {
      if (operation.includes('投票')) return 'tag-vote'
      if (operation.includes('团队') || operation.includes('解散')) return 'tag-team'
      if (operation.includes('手动')) return 'tag-manual'
      if (operation.includes('回滚')) return 'tag-rollback'
      return 'tag-other'
    },
    
    // 截断文件名显示
    truncateFileName(fileName) {
      return fileName.length > 20 ? fileName.substring(0, 20) + '...' : fileName
    }
  }
}
</script>

<style scoped>
.sql-history-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60rpx 40rpx;
  text-align: center;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.header-title {
  font-size: 48rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 20rpx;
}

.header-subtitle {
  font-size: 28rpx;
  opacity: 0.9;
}

.dashboard {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.stat-card {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
  text-align: center;
  box-shadow: 0 10rpx 30rpx rgba(0,0,0,0.1);
}

.stat-label {
  color: #666;
  font-size: 24rpx;
  display: block;
  margin-bottom: 20rpx;
  text-transform: uppercase;
  letter-spacing: 2rpx;
}

.stat-value {
  font-size: 48rpx;
  font-weight: bold;
  color: #667eea;
}

.controls {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.btn {
  padding: 24rpx 48rpx;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-success {
  background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
  color: white;
}

.btn-danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
}

.btn-sm {
  padding: 16rpx 32rpx;
  font-size: 24rpx;
}

.last-update {
  color: #666;
  font-size: 24rpx;
}

.alert {
  padding: 30rpx;
  margin: 20rpx 0;
  border-radius: 16rpx;
  font-weight: 500;
}

.alert-success {
  background: #d4edda;
  color: #155724;
  border: 2rpx solid #c3e6cb;
}

.alert-danger {
  background: #f8d7da;
  color: #721c24;
  border: 2rpx solid #f5c6cb;
}

.history-table {
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
  background: #f8f9fa;
  padding: 30rpx 20rpx;
  font-weight: 600;
  color: #495057;
}

.header-cell {
  text-align: center;
  font-size: 24rpx;
}

.table-body {
  max-height: 800rpx;
  overflow-y: auto;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
  padding: 30rpx 20rpx;
  border-bottom: 2rpx solid #eee;
  align-items: center;
}

.table-cell {
  text-align: center;
  font-size: 24rpx;
  word-break: break-all;
}

.filename {
  color: #666;
}

.operation-tag {
  display: inline-block;
  padding: 8rpx 24rpx;
  border-radius: 40rpx;
  font-size: 20rpx;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1rpx;
}

.tag-vote { background: #e3f2fd; color: #1976d2; }
.tag-team { background: #f3e5f5; color: #7b1fa2; }
.tag-manual { background: #e8f5e8; color: #388e3c; }
.tag-rollback { background: #fff3e0; color: #f57c00; }
.tag-other { background: #f5f5f5; color: #616161; }

.loading, .empty {
  text-align: center;
  padding: 100rpx;
  color: #666;
  font-size: 28rpx;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  margin: 30rpx;
  padding: 60rpx;
  border-radius: 30rpx;
  width: 90%;
  max-width: 800rpx;
  box-shadow: 0 40rpx 80rpx rgba(0,0,0,0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 48rpx;
  color: #aaa;
  cursor: pointer;
}

.modal-body {
  margin-bottom: 40rpx;
}

.modal-text {
  font-size: 28rpx;
  margin-bottom: 20rpx;
  display: block;
}

.backup-info {
  background: #f8f9fa;
  padding: 30rpx;
  border-radius: 16rpx;
  margin: 30rpx 0;
}

.backup-name {
  font-weight: bold;
  font-size: 28rpx;
  display: block;
  margin-bottom: 10rpx;
}

.backup-details {
  font-size: 24rpx;
  color: #666;
}

.form-group {
  margin-bottom: 40rpx;
}

.form-label {
  display: block;
  margin-bottom: 16rpx;
  font-weight: 600;
  color: #555;
  font-size: 28rpx;
}

.optional {
  color: #999;
  font-weight: normal;
}

.form-textarea {
  width: 100%;
  padding: 24rpx;
  border: 4rpx solid #e9ecef;
  border-radius: 16rpx;
  font-size: 28rpx;
  min-height: 120rpx;
  box-sizing: border-box;
}

.warning-text {
  color: #dc3545;
  font-weight: 600;
  font-size: 24rpx;
}

.modal-footer {
  display: flex;
  gap: 30rpx;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .dashboard {
    grid-template-columns: 1fr;
  }
  
  .controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .table-header, .table-row {
    grid-template-columns: 1fr;
    gap: 10rpx;
  }
  
  .header-cell, .table-cell {
    text-align: left;
    padding: 10rpx;
  }
}
</style>



